import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Spin, Button, Tag, message, Breadcrumb } from 'antd';
import { useError } from '../../components/ui/ErrorHandler';
import { useLoading } from '../../components/ui/LoadingManager';
import Loading from '../../components/ui/Loading';
import { 
  ArrowLeftOutlined, 
  PhoneOutlined, 
  MessageOutlined, 
  HeartOutlined,
  ShareAltOutlined,
  HomeOutlined,
  ProjectOutlined,
  CheckCircleOutlined,
  StarFilled,
  CalendarOutlined,
  EnvironmentOutlined,
  UserOutlined,
  ClockCircleOutlined,
  DollarOutlined
} from '@ant-design/icons';
import ContactModal from '../../components/ui/ContactModal';

// 案例接口定义
interface Case {
  id: string;
  title: string;
  description?: string;
  category: string;
  client: string;
  completedAt: string;
  images: string[];
  tags?: string[];
  location?: string;
  projectValue?: string;
  duration?: string;
  featured: boolean;
  status: string;
  challenges?: string;
  solutions?: string;
  results?: string;
  technologies?: Technology[];
  createdAt: string;
  updatedAt: string;
}

// 技术规格接口
interface Technology {
  name: string;
  description: string;
  specifications?: TechSpec[];
}

// 技术规格接口
interface TechSpec {
  name: string;
  value: string;
  unit?: string;
}

const CaseDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { showError } = useError();
  const { withLoading } = useLoading();
  const [caseData, setCaseData] = useState<Case | null>(null);
  const [loading, setLoading] = useState(true);
  const [contactModalOpen, setContactModalOpen] = useState(false);
  const [selectedImageIndex, setSelectedImageIndex] = useState(0);

  // 模拟案例数据
  const mockCase: Case = {
    id: '1',
    title: '某知名连锁餐厅LED发光字制作',
    description: '为知名连锁餐厅制作高品质LED发光字，提升品牌形象，增强夜间识别度。采用优质LED灯珠，确保长期稳定运行，为客户打造专业的品牌形象展示。',
    category: 'signage',
    client: '某知名连锁餐厅',
    completedAt: '2024-01-15',
    images: [
      'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=restaurant%20LED%20illuminated%20signage%20night%20view%20modern%20design%20commercial%20storefront&image_size=landscape_16_9',
      'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=LED%20channel%20letters%20restaurant%20brand%20signage%20professional%20installation&image_size=landscape_16_9',
      'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=restaurant%20exterior%20LED%20signage%20daytime%20view%20modern%20architecture&image_size=landscape_16_9',
      'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=LED%20signage%20installation%20process%20professional%20workers%20commercial%20building&image_size=landscape_16_9'
    ],
    tags: ['LED发光字', '餐饮行业', '连锁品牌', '夜间照明'],
    location: '上海市浦东新区',
    projectValue: '15万元',
    duration: '15天',
    featured: true,
    status: 'completed',
    challenges: '客户要求在不影响正常营业的情况下完成安装，同时需要确保LED发光字在各种天气条件下都能正常工作，并且要与餐厅的整体装修风格保持一致。',
    solutions: '我们采用了模块化设计方案，在工厂预制所有组件，现场快速组装。选用了防水等级IP65的LED模组，确保在恶劣天气下也能稳定工作。设计团队与客户深度沟通，确保发光字的颜色、字体与品牌形象完美匹配。',
    results: '项目按时完成，LED发光字在夜间效果显著，大大提升了餐厅的品牌识别度。客户反馈非常满意，夜间客流量较之前增加了30%。发光字运行稳定，至今无故障记录。',
    technologies: [
      {
        name: 'LED发光技术',
        description: '采用高品质LED灯珠，确保亮度均匀、色彩一致',
        specifications: [
          { name: '亮度', value: '3000', unit: '流明' },
          { name: '色温', value: '6500', unit: 'K' },
          { name: '功耗', value: '12', unit: 'W/米' },
          { name: '寿命', value: '50000', unit: '小时' }
        ]
      },
      {
        name: '防水防尘技术',
        description: '采用IP65防护等级，适应各种恶劣天气条件',
        specifications: [
          { name: '防护等级', value: 'IP65' },
          { name: '工作温度', value: '-20~60', unit: '℃' },
          { name: '湿度范围', value: '10~90', unit: '%RH' }
        ]
      },
      {
        name: '智能控制系统',
        description: '支持远程控制和定时开关，节能环保',
        specifications: [
          { name: '控制方式', value: '无线遥控' },
          { name: '定时功能', value: '支持' },
          { name: '调光范围', value: '10-100', unit: '%' }
        ]
      }
    ],
    createdAt: '2024-01-01',
    updatedAt: '2024-01-15'
  };

  useEffect(() => {
    const fetchCase = async () => {
      if (!id) {
        showError('案例ID不存在');
        navigate('/cases');
        return;
      }
      
      try {
        setLoading(true);
        // 调用真实API获取案例详情
        const response = await fetch(`/api/cases/${id}`);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const result = await response.json();
        if (result.success && result.data) {
          setCaseData(result.data);
        } else {
          throw new Error(result.message || '获取案例详情失败');
        }
      } catch (error) {
        console.error('获取案例详情失败:', error);
        showError(error instanceof Error ? error : '获取案例详情失败', {
          modal: true,
          details: '请检查网络连接或稍后重试'
        });
        // 如果API失败，使用模拟数据作为后备
        setCaseData(mockCase);
      } finally {
        setLoading(false);
      }
    };

    fetchCase();
  }, [id, showError, withLoading, navigate]);

  if (loading) {
    return (
      <Loading 
        text="正在加载案例详情..." 
        overlay={true}
        size="large"
      />
    );
  }

  if (!caseData) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-gray-600 mb-4">案例不存在</h2>
          <Button onClick={() => navigate('/cases')} type="primary">
            返回案例列表
          </Button>
        </div>
      </div>
    );
  }

  const getCategoryLabel = (category: string) => {
    // 如果分类本身就是中文名称，直接返回
    if (category && /[\u4e00-\u9fa5]/.test(category)) {
      return category;
    }
    // 英文分类ID到中文名称的映射
    const categories: { [key: string]: string } = {
      // 新的分类映射
      'shopping-mall': '商业地产',
      'corporate': '企业形象',
      'restaurant': '餐饮行业',
      'retail': '零售行业',
      'education': '教育培训',
      'healthcare': '医疗健康',
      'finance': '金融服务',
      'real-estate': '房地产',
      'automotive': '汽车服务',
      'manufacturing': '制造业',
      'government': '政府机构',
      'entertainment': '文化娱乐',
      'technology': '科技企业',
      'hotel': '酒店行业',
      'beauty': '美容美发',
      // 兼容旧的英文分类映射
      'signage': '标识标牌',
      'led_display': 'LED显示屏',
      'neon_sign': '霓虹灯',
      'acrylic_sign': '亚克力制品',
      'metal_sign': '金属标识',
      'outdoor_ad': '户外广告',
      'indoor_decoration': '室内装饰',
      'exhibition': '展览展示'
    };
    return categories[category] || category;
  };

  const getCategoryColor = (category: string) => {
    // 为不同分类提供不同的背景颜色
    const colorMap: { [key: string]: string } = {
      'shopping-mall': 'bg-gradient-to-r from-blue-500 to-blue-600',
      'corporate': 'bg-gradient-to-r from-gray-600 to-gray-700',
      'restaurant': 'bg-gradient-to-r from-orange-500 to-red-500',
      'retail': 'bg-gradient-to-r from-green-500 to-emerald-500',
      'education': 'bg-gradient-to-r from-indigo-500 to-purple-500',
      'healthcare': 'bg-gradient-to-r from-teal-500 to-cyan-500',
      'finance': 'bg-gradient-to-r from-yellow-500 to-amber-500',
      'real-estate': 'bg-gradient-to-r from-stone-500 to-neutral-600',
      'automotive': 'bg-gradient-to-r from-slate-600 to-gray-700',
      'manufacturing': 'bg-gradient-to-r from-zinc-500 to-stone-600',
      'government': 'bg-gradient-to-r from-red-600 to-rose-600',
      'entertainment': 'bg-gradient-to-r from-pink-500 to-rose-500',
      'technology': 'bg-gradient-to-r from-violet-500 to-purple-600',
      'hotel': 'bg-gradient-to-r from-amber-500 to-orange-500',
      'beauty': 'bg-gradient-to-r from-fuchsia-500 to-pink-500',
      // 中文分类的颜色映射
      '餐饮行业': 'bg-gradient-to-r from-orange-500 to-red-500',
      '零售行业': 'bg-gradient-to-r from-green-500 to-emerald-500',
      '教育培训': 'bg-gradient-to-r from-indigo-500 to-purple-500',
      '医疗健康': 'bg-gradient-to-r from-teal-500 to-cyan-500',
      '金融服务': 'bg-gradient-to-r from-yellow-500 to-amber-500',
      '房地产': 'bg-gradient-to-r from-stone-500 to-neutral-600',
      '汽车服务': 'bg-gradient-to-r from-slate-600 to-gray-700',
      '制造业': 'bg-gradient-to-r from-zinc-500 to-stone-600',
      '政府机构': 'bg-gradient-to-r from-red-600 to-rose-600',
      '文化娱乐': 'bg-gradient-to-r from-pink-500 to-rose-500'
    };
    return colorMap[category] || 'bg-gradient-to-r from-purple-500 to-purple-600';
  };

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 顶部导航 */}
      <div className="bg-white shadow-sm sticky top-0 z-10">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <Button 
                icon={<ArrowLeftOutlined />}
                onClick={() => navigate('/cases')}
                type="text"
                shape="circle"
                size="large"
                className="text-purple-600 hover:text-purple-700 hover:bg-purple-50"
              />
              <Breadcrumb
                items={[
                  {
                    title: (
                      <div className="flex items-center gap-1 text-gray-600">
                        <HomeOutlined />
                        <span>首页</span>
                      </div>
                    ),
                    onClick: () => navigate('/')
                  },
                  {
                    title: (
                      <div className="flex items-center gap-1 text-gray-600">
                        <ProjectOutlined />
                        <span>合作案例</span>
                      </div>
                    ),
                    onClick: () => navigate('/cases')
                  },
                  {
                    title: caseData.title
                  }
                ]}
              />
            </div>
            <div className="flex items-center gap-2">
              <Button 
                icon={<ShareAltOutlined />} 
                type="text"
                onClick={() => {
                  navigator.clipboard.writeText(window.location.href);
                  message.success('链接已复制到剪贴板');
                }}
              >
                分享
              </Button>
            </div>
          </div>
        </div>
      </div>

      <div className="container mx-auto px-3 sm:px-4 py-4 sm:py-6 md:py-8">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6 md:gap-8 lg:gap-12">
          {/* 左侧案例图片 */}
          <div className="space-y-3 sm:space-y-4">
            {/* 主图 */}
            <div className="bg-white rounded-lg overflow-hidden shadow-lg border border-gray-200" style={{ aspectRatio: '16/13.5' }}>
              <img
                src={caseData.images[selectedImageIndex] || 'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=professional%20advertising%20case%20study%20modern%20signage%20project&image_size=landscape_16_9'}
                alt={caseData.title}
                className="w-full h-full object-cover hover:scale-105 transition-transform duration-300"
              />
            </div>
            
            {/* 缩略图 */}
            {caseData.images.length > 1 && (
              <div className="flex gap-2 overflow-x-auto pb-2">
                {caseData.images.map((image, index) => (
                  <div
                    key={index}
                    className={`flex-shrink-0 w-16 h-10 sm:w-20 sm:h-12 rounded-lg overflow-hidden cursor-pointer border-2 transition-all duration-300 ${
                      selectedImageIndex === index ? 'border-purple-500 shadow-lg' : 'border-gray-200 hover:border-purple-300'
                    }`}
                    onClick={() => setSelectedImageIndex(index)}
                  >
                    <img
                      src={image}
                      alt={`${caseData.title} ${index + 1}`}
                      className="w-full h-full object-cover"
                    />
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* 右侧案例信息 */}
          <div className="space-y-4 sm:space-y-6">
            {/* 基本信息 */}
            <div className="bg-white rounded-lg p-4 sm:p-6 shadow-sm border border-gray-200">
              <h1 className="text-xl sm:text-2xl md:text-3xl lg:text-4xl font-bold bg-gradient-to-r from-gray-900 via-purple-800 to-blue-800 bg-clip-text text-transparent mb-2">{caseData.title}</h1>

              
              <p className="text-sm sm:text-base text-gray-700 mb-4 leading-relaxed">{caseData.description}</p>
              
              {/* 案例信息 */}
              <div className="space-y-3 mb-4">
                <div className="flex items-center gap-2">
                  <span className="text-gray-600 font-medium">分类：</span>
                  <Tag className={`border-0 text-white font-medium px-3 py-1 rounded-lg ${
                    getCategoryColor(caseData.category)
                  }`}>
                    {getCategoryLabel(caseData.category)}
                  </Tag>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-gray-600 font-medium">标签：</span>
                  <div className="flex flex-wrap gap-2">
                    {caseData.tags?.map((tag, index) => (
                      <Tag key={index} color="blue">{tag}</Tag>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* 项目详情 */}
            <div className="bg-white rounded-lg p-4 sm:p-6 shadow-sm border border-gray-200">
              <h3 className="text-base sm:text-lg font-bold text-gray-900 mb-3 sm:mb-4">项目详情</h3>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 sm:gap-3">
                <div className="flex items-center gap-2 sm:gap-3 p-2 sm:p-3 bg-gray-50 rounded-lg">
                  <UserOutlined className="text-purple-500 text-base sm:text-lg" />
                  <div className="font-semibold text-gray-900 text-xs sm:text-sm">{caseData.client}</div>
                </div>
                <div className="flex items-center gap-2 sm:gap-3 p-2 sm:p-3 bg-gray-50 rounded-lg">
                  <EnvironmentOutlined className="text-green-500 text-base sm:text-lg" />
                  <div className="font-semibold text-gray-900 text-xs sm:text-sm">{caseData.location}</div>
                </div>
                <div className="flex items-center gap-2 sm:gap-3 p-2 sm:p-3 bg-gray-50 rounded-lg">
                  <ClockCircleOutlined className="text-orange-500 text-base sm:text-lg" />
                  <div className="font-semibold text-gray-900 text-xs sm:text-sm">{caseData.duration}</div>
                </div>
                <div className="flex items-center gap-2 sm:gap-3 p-2 sm:p-3 bg-gray-50 rounded-lg">
                  <CalendarOutlined className="text-red-500 text-base sm:text-lg" />
                  <div className="font-semibold text-gray-900 text-xs sm:text-sm">{caseData.completedAt}</div>
                </div>
              </div>
            </div>

            {/* 立刻咨询按钮 */}
            <div className="bg-white rounded-lg p-4 sm:p-6 shadow-sm border border-gray-200">
              <Button
                type="primary"
                size="large"
                icon={<PhoneOutlined />}
                className="w-full h-10 sm:h-12 text-sm sm:text-lg font-semibold bg-purple-600 hover:bg-purple-700"
                onClick={() => setContactModalOpen(true)}
              >
                咨询类似项目
              </Button>
              
              <div className="mt-3 sm:mt-4 text-center">
                <p className="text-xs sm:text-sm text-gray-500">
                  💡 专业团队为您提供类似项目的定制化解决方案
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* 详细信息区域 */}
        <div className="mt-6 sm:mt-8 md:mt-12 space-y-4 sm:space-y-6 md:space-y-8">
          {/* 项目背景 */}
          {caseData.challenges && (
            <div className="bg-white rounded-lg p-4 sm:p-6 md:p-8 shadow-sm border border-gray-200">
              <h2 className="text-lg sm:text-xl md:text-2xl font-bold text-gray-900 mb-4 sm:mb-6">项目背景</h2>
              <div className="prose prose-sm sm:prose-base md:prose-lg max-w-none">
                <p className="text-gray-700 leading-relaxed text-sm sm:text-base">{caseData.challenges}</p>
              </div>
            </div>
          )}

          {/* 解决方案 */}
          {caseData.solutions && (
            <div className="bg-white rounded-lg p-4 sm:p-6 md:p-8 shadow-sm border border-gray-200">
              <h2 className="text-lg sm:text-xl md:text-2xl font-bold text-gray-900 mb-4 sm:mb-6">解决方案</h2>
              <div className="prose prose-sm sm:prose-base md:prose-lg max-w-none">
                <p className="text-gray-700 leading-relaxed text-sm sm:text-base">{caseData.solutions}</p>
              </div>
            </div>
          )}

          {/* 技术规格 */}
          {caseData.technologies && caseData.technologies.length > 0 && (
            <div className="bg-white rounded-lg p-4 sm:p-6 md:p-8 shadow-sm border border-gray-200">
              <h2 className="text-lg sm:text-xl md:text-2xl font-bold text-gray-900 mb-4 sm:mb-6">技术规格</h2>
              <div className="space-y-4 sm:space-y-6">
                {caseData.technologies.map((tech, index) => (
                  <div key={index} className="border border-gray-200 rounded-lg p-3 sm:p-4 md:p-6">
                    <h3 className="text-base sm:text-lg font-semibold text-gray-900 mb-2">{tech.name}</h3>
                    <p className="text-sm sm:text-base text-gray-600 mb-3 sm:mb-4">{tech.description}</p>
                    {tech.specifications && tech.specifications.length > 0 && (
                      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2 sm:gap-3 md:gap-4">
                        {tech.specifications.map((spec, specIndex) => (
                          <div key={specIndex} className="bg-gray-50 rounded-lg p-2 sm:p-3">
                            <div className="flex items-center justify-between">
                              <span className="text-xs sm:text-sm text-gray-600 font-medium">{spec.name}：</span>
                              <span className="text-xs sm:text-sm text-gray-900 font-semibold">{spec.value} {spec.unit || ''}</span>
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 项目成果 */}
          {caseData.results && (
            <div className="bg-white rounded-lg p-4 sm:p-6 md:p-8 shadow-sm border border-gray-200">
              <h2 className="text-lg sm:text-xl md:text-2xl font-bold text-gray-900 mb-4 sm:mb-6">项目成果</h2>
              <p className="text-sm sm:text-base md:text-lg text-gray-700 leading-relaxed">{caseData.results}</p>
            </div>
          )}

          {/* 服务保障 */}
          <div className="bg-white rounded-lg p-4 sm:p-6 md:p-8 shadow-sm border border-gray-200">
            <h2 className="text-lg sm:text-xl md:text-2xl font-bold text-gray-900 mb-4 sm:mb-6">服务保障</h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
              <div className="text-center">
                <div className="w-12 h-12 sm:w-16 sm:h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-3 sm:mb-4">
                  <CheckCircleOutlined className="text-lg sm:text-2xl text-purple-600" />
                </div>
                <h3 className="text-sm sm:text-base font-semibold text-gray-900 mb-2">质量保证</h3>
                <p className="text-xs sm:text-sm text-gray-600">严格的质量控制体系，确保每个项目都达到最高标准</p>
              </div>
              <div className="text-center">
                <div className="w-12 h-12 sm:w-16 sm:h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-3 sm:mb-4">
                  <PhoneOutlined className="text-lg sm:text-2xl text-green-600" />
                </div>
                <h3 className="text-sm sm:text-base font-semibold text-gray-900 mb-2">24小时服务</h3>
                <p className="text-xs sm:text-sm text-gray-600">7×24小时客服支持，随时为您解答疑问</p>
              </div>
              <div className="text-center">
                <div className="w-12 h-12 sm:w-16 sm:h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-3 sm:mb-4">
                  <MessageOutlined className="text-lg sm:text-2xl text-blue-600" />
                </div>
                <h3 className="text-sm sm:text-base font-semibold text-gray-900 mb-2">技术支持</h3>
                <p className="text-xs sm:text-sm text-gray-600">专业技术团队提供全程技术支持和指导</p>
              </div>
              <div className="text-center">
                <div className="w-12 h-12 sm:w-16 sm:h-16 bg-orange-100 rounded-full flex items-center justify-center mx-auto mb-3 sm:mb-4">
                  <StarFilled className="text-lg sm:text-2xl text-orange-600" />
                </div>
                <h3 className="text-sm sm:text-base font-semibold text-gray-900 mb-2">售后保障</h3>
                <p className="text-xs sm:text-sm text-gray-600">完善的售后服务体系，让您无后顾之忧</p>
              </div>
            </div>
          </div>


        </div>
      </div>

      {/* 联系弹窗 */}
      <ContactModal
        open={contactModalOpen}
        onClose={() => setContactModalOpen(false)}
      />
    </div>
  );
};

export default CaseDetailPage;